<template>
  <ElForm
    ref="form"
    class="clear-fix"
    :model="model"
    :size="size"
    :disabled="disabled"
    :label-width="labelWidth"
    :label-position="labelPosition">
    <slot></slot>
  </ElForm>
</template>

<script>
  import { warning } from '@web-utils/core'
  import { findParent } from '@/util'

  export default {
    name: 'FormHolder',
    provide() {
      return {
        formHolder: this
      }
    },
    props: {
      model: Object,
      size: {
        type: String,
        default: 'mini'
      },
      disabled: Boolean,
      labelPosition: {
        type: String,
        default: 'right'
      },
      labelWidth: {
        type: String,
        default: '110px'
      },
      required: {
        type: Boolean,
        default: true
      },
      requiredFields: Array,
      enabledFields: Array
    },
    watch: {
      required() {
        this.clearValidate()
      }
    },
    created() {
      if (!this.required) {
        warning.call(
          findParent(this, parent => ['FormView', 'FormHolder'].includes(parent.$options.name)),
          '一般情况下不建议设置 required=false,因为 required 设置为 false 后必填字段要自行维护,在处理表格时会比较复杂,请自行权衡利弊'
        )
      }
    },
    methods: {
      clearValidate(fields) {
        this.$refs.form?.clearValidate(fields)
      },
      async validate() {
        try {
          return await this.$refs.form.validate()
        } catch (e) {
          await this.scrollIntoRequiredField()
          throw Error('表单验证不通过!')
        }
      },
      resetFields() {
        return this.$refs.form.resetFields()
      },
      async scrollIntoRequiredField() {
        await this.$nextTick()
        const requiredField = this.$el.querySelector('.el-form-item.is-error.is-required')
        if (requiredField) {
          requiredField.scrollIntoView()
        }
      }
    }
  }
</script>
